package com.hksj.common.config.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * 分页统一返回结果
 * 1.使用MyBatis-Plus/JPA分页插件先进行分页
 * 2.调用restPage方法将第1步的分页结果封装成PageResult
 * 3.使用Rest.ok(T data) 方法返回 PageResult
 */
@Data
public final class PageResult<T> {
    private final long pageNum;
    private final long pageSize;
    private final long total;
    private final List<T> list;

    private PageResult(@NonNull Long pageNum, @NonNull Long pageSize, @NonNull Long total, @Nullable List<T> list) {
        this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.total = total;
        this.list = list;
    }


    public static <T> PageResult<T> restPage(@NonNull Long pageNum, @NonNull Long pageSize, @NonNull Long total, @Nullable List<T> list) {
        return new PageResult<>(pageNum, pageSize, total, Optional.ofNullable(list).orElse(Collections.emptyList()));
    }

    /**
     * 将MyBatis Plus 分页结果转化为通用结果
     *
     */
    public static <T> PageResult<T> restPage(@NonNull IPage<T> page) {
        return new PageResult<>(page.getCurrent(), page.getSize(), page.getTotal(), page.getRecords());
    }


    /**
     * 将Jpa分页结果转化为通用结果
     */
    public static <T> PageResult<T> restPage(@NonNull org.springframework.data.domain.Page<T> page) {
        return new PageResult<>((long) page.getNumber()+1, (long) page.getSize(), page.getTotalElements(), page.getContent());
    }

}
